#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#include "cJSON.h"
#include <stdlib.h>

#define LOG_PATH	"/home/work/share64/filetree.csv"
//#define LOG_PATH	"/mnt/nandflash/filetree.csv"

int ReadDir(const char *path, cJSON * root)
{
	DIR *dir;
	struct dirent *d_stat;
	char file[512] = {0};
	char log[512] = {0};
	struct stat f_stat;
	char mode[12] = {0};
	unsigned char f_mode = 0;
	unsigned int mode_mask = 0;
	int i = 0, j = 0;
	static unsigned int total = 0;
	time_t f_time;
	char *pTime = NULL;

	if((!root) || (!path)){
		return -1;
	}
	
	memset(&f_stat, 0, sizeof(f_stat));
	stat(path, &f_stat);
	if(!(S_IFDIR & f_stat.st_mode)){
		printf("%s is not dir \n", path);
		return 0;
	}

	dir = opendir(path);
	if(!dir){
		printf("opendir %s failed \n",path);
		perror("openfile");
		return -1;
	}

	cJSON *arr;

	arr = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "files", arr);

	while(d_stat = readdir(dir)){
		if(!strcmp(d_stat->d_name, ".") || !strcmp(d_stat->d_name, "..")){
			continue;
		}
		memset(file, 0, sizeof(file));
		memset(&f_stat, 0, sizeof(f_stat));
		sprintf(file, "%s/%s",path, d_stat->d_name);
		stat(file, &f_stat);
		if(S_IFDIR & f_stat.st_mode){
			cJSON *item = cJSON_CreateObject();
			cJSON_AddItemToObject(root, d_stat->d_name, item);
			ReadDir(file, item);
		}
		else{
			cJSON_AddItemToArray(arr, cJSON_CreateString(d_stat->d_name));
		}
	}
	closedir(dir);
	
	return 0;
}


int main()
{
	cJSON *root;
	char *path = "/mnt/hgfs/share64/log";

	root = cJSON_CreateObject();
	if(!root){
		return -1;
	}	
	ReadDir(path, root);
	cJSON *item = cJSON_CreateString("hello");
	char *p = cJSON_PrintUnformatted(item);
	if(p){
		printf("%s \n", p);
		free(p);
	}
	
	cJSON_Delete(root);
}
